import { compareVersion } from '../common'

/**
 * 检测是否支持webp
 */
const isWebpSupported = () => {
  const { osName } = uni.getSystemInfoSync()
  /** 是否IOS环境 */
  const isIOS = osName === 'ios'
  /** 是否安卓环境 */
  const isAndroid = osName === 'android'

  try {
    const { osVersion, SDKVersion } = uni.getSystemInfoSync()

    // #ifdef WEB
    return (
      document.createElement('canvas').toDataURL('image/webp', 0.5).indexOf('data:image/webp') === 0
    )
    // #endif

    // #ifdef MP-WEIXIN
    if (SDKVersion && compareVersion(SDKVersion, '2.9.0') < 0) {
      return false
    }
    // #endif

    if (isAndroid && compareVersion(osVersion, '4.2.0') >= 0) {
      return true
    }

    if (isIOS && compareVersion(osVersion, '14.0.0') >= 0) {
      return true
    }
  } catch (e) {
    console.error(e)
  }

  return false
}

/** 是否支持webp */
const supportWebp = isWebpSupported()

/** 支持webp格式 */
const canUseWebpFormat: Record<string, boolean> = {
  jpg: true,
  jpeg: true,
  png: true,
}

export { isWebpSupported, supportWebp, canUseWebpFormat }
